from datetime import datetime

import bcrypt
import pymysql
from flask import jsonify, render_template, request, current_app, abort
from config.config import DB_CONFIG
from werkzeug.utils import secure_filename
import os
from config.config import url
import time


def get_url():
    return url


def get_db_connection():
    return pymysql.connect(**DB_CONFIG)


def buy():
    username = request.cookies.get('username')
    token = request.cookies.get('token')

    # 检查用户名和令牌是否存在
    if not username or not token:
        abort(402, description="未授权：缺少用户名或令牌")

    # 检查令牌是否有效
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
    results = cursor.fetchall()

    # 遍历查询结果，检查是否有匹配的token
    for result in results:
        if result[0] == token:
            break
    else:
        cursor.close()
        conn.close()
        abort(403, description="未授权：无效的令牌")

    # 从请求中获取商品ID
    product_id = request.form.get('id')
    # 从请求中获取商品ID
    product_id = request.form.get('id')

    # 查询商品记录，检查who_buy字段
    cursor.execute(
        "SELECT who_buy FROM Products WHERE ProductID = %s",
        (product_id,)
    )
    who_buy = cursor.fetchone()[0]

    # 如果who_buy字段已经有值，说明商品已经被预订
    if who_buy:
        return jsonify({'status': 'error', 'msg': '商品已经被预订'})

    # 更新商品记录，将用户名存入who_buy字段
    cursor.execute(
        "UPDATE Products SET who_buy = %s WHERE ProductID = %s",
        (username, product_id)
    )
    conn.commit()
    cursor.close()
    conn.close()

    return jsonify({'status': 'success', 'msg': '购买成功'})


def get_my_buys():
    username = request.cookies.get('username')
    token = request.cookies.get('token')

    # 检查用户名和令牌是否存在
    if not username or not token:
        abort(402, description="未授权：缺少用户名或令牌")

    # 检查令牌是否有效
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
    results = cursor.fetchall()

    # 遍历查询结果，检查是否有匹配的token
    for result in results:
        if result[0] == token:
            break
    else:
        cursor.close()
        conn.close()
        abort(403, description="未授权：无效的令牌")

    # 查询用户购买的所有商品
    cursor.execute(
        "SELECT ProductID, ProductName, Price, ImageURL, success_shipments, IsSold FROM Products WHERE who_buy = %s",
        (username,)
    )
    products = cursor.fetchall()

    data = []
    for product in products:
        data.append({
            'ProductID': product[0],
            'ProductName': product[1],
            'Price': product[2],
            'ImageURL': product[3],
            'success_shipments': product[4],
            'IsSold': product[5]  # 添加 IsSold 字段
        })

    cursor.close()
    conn.close()

    return jsonify({'status': 'success', 'data': data})

def success_buy():
    username = request.cookies.get('username')
    token = request.cookies.get('token')

    # 检查用户名和令牌是否存在
    if not username or not token:
        abort(402, description="未授权：缺少用户名或令牌")

    # 检查令牌是否有效
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
    results = cursor.fetchall()

    # 遍历查询结果，检查是否有匹配的token
    for result in results:
        if result[0] == token:
            break
    else:
        cursor.close()
        conn.close()
        abort(403, description="未授权：无效的令牌")

    # 从请求中获取商品ID
    product_id = request.get_json().get('product_id')
    print(product_id)
    # 更新商品记录，将IsSold字段设置为1
    cursor.execute(
        "UPDATE Products SET IsSold = 1 WHERE ProductID = %s",
        (product_id,)
    )
    conn.commit()
    cursor.close()
    conn.close()

    return jsonify({'status': 'success', 'msg': '确认收货成功'})
def check_buy():
    username = request.cookies.get('username')
    token = request.cookies.get('token')

    # 检查用户名和令牌是否存在
    if not username or not token:
        abort(402, description="未授权：缺少用户名或令牌")

    # 检查令牌是否有效
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
    results = cursor.fetchall()

    # 遍历查询结果，检查是否有匹配的token
    for result in results:
        if result[0] == token:
            break
    else:
        cursor.close()
        conn.close()
        abort(403, description="未授权：无效的令牌")

    # 从请求中获取商品ID
    product_id = request.form.get('id')
    print(product_id)

    # 查询商品记录，检查who_buy字段
    cursor.execute(
        "SELECT who_buy FROM Products WHERE ProductID = %s",
        (product_id,)
    )
    who_buy = cursor.fetchone()[0]

    cursor.close()
    conn.close()

    # 检查who_buy字段是否有值
    if who_buy:
        # 如果who_buy字段的值与cookie中的username字段值一致
        if who_buy == username:
            return jsonify({'status': 'success', 'msg': '可以取消预订'})
        else:
            return jsonify({'status': 'success', 'msg': '已被预订'})
    else:
        return jsonify({'status': 'success', 'msg': '可以预订'})

def delete_buy():
    username = request.cookies.get('username')
    token = request.cookies.get('token')

    # 检查用户名和令牌是否存在
    if not username or not token:
        abort(402, description="未授权：缺少用户名或令牌")

    # 检查令牌是否有效
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
    results = cursor.fetchall()

    # 遍历查询结果，检查是否有匹配的token
    for result in results:
        if result[0] == token:
            break
    else:
        cursor.close()
        conn.close()
        abort(403, description="未授权：无效的令牌")

    # 从请求中获取商品ID
    product_id = request.form.get('id')

    # 更新商品记录，将who_buy字段置空
    cursor.execute(
        "UPDATE Products SET who_buy = NULL WHERE ProductID = %s",
        (product_id,)
    )
    conn.commit()
    cursor.close()
    conn.close()

    return jsonify({'status': 'success', 'msg': '取消预订成功'})





class Buy:
    def __init__(self, app):
        self.app = app
        self.app.add_url_rule('/api/buy', view_func=buy, methods=['POST'])
        self.app.add_url_rule('/api/check_buy', view_func=check_buy, methods=['POST'])
        self.app.add_url_rule('/api/delete_buy', view_func=delete_buy, methods=['POST'])
        self.app.add_url_rule('/api/my_buys', view_func=get_my_buys, methods=['GET'])
        self.app.add_url_rule('/api/success_buy', view_func=success_buy, methods=['POST'])

